$(document).ready(function () {

  var firstimevisit = $.cookie('firsttime');

  if(!firstimevisit){
    $.cookie('firsttime', 'true', { expires: 7 });
    $('#welcome').modal('show');
  };

  $("#name .question").click( function(){
    $('#welcome').modal('show');
    return false;
  });

  // Variables

  var timer = null;
  var def = 1;
  var live = 0;

  var date = new Date().getDate() + "" + new Date().getMonth() + "" + new Date().getFullYear();
  var cookieNumberOfCycles = $.cookie(date);

  var soundAlert = new Audio("media/alert.wav");

  var namePomodoro = $("#name span.pomodoro").text();
  var nameBreak = $("#name span.break").text();
  var descPomodoro = $("#desc span.pomodoro").text();
  var descBreak = $("#desc span.break").text();
  $("#name span.break, #desc").remove();

  if(cookieNumberOfCycles){
    numberOfCycles = cookieNumberOfCycles;
    $("#numberofcycles span").text(numberOfCycles);
  } else {
    $.cookie(date, 0);
    numberOfCycles = 0;
  };

  // Chrome and notification
  if(/chrom(e|ium)/.test(navigator.userAgent.toLowerCase())){
   var browserChrome = true;
  };

  $("#permission").hide();

  if(browserChrome == true){

    if (window.webkitNotifications.checkPermission() != 0){
      $("#permission").show();
    };

    $("#permission button").click( function(){
      window.webkitNotifications.requestPermission();
      $("#permission").slideUp();
      return false;
    });

  };

  // Functions
  function formatTimeOfDay(value) {
    var secondsSinceEpoch = (value / 1000) | 0;
    var secondsInDay = ((secondsSinceEpoch % 86400) + 86400) % 86400;
    var seconds = secondsInDay % 60;
    var minutes = ((secondsInDay / 60) | 0) % 60;
    return minutes + (seconds < 10 ? ":0" : ":") + seconds
  };

  // Start and stop button

  $("#control").click(function(){

    // $("#skipbreak").fadeIn();

    if(live == 0){
      core();
      $("#control").find("span").text("Stop");
      $("#control").children().addClass("btn-danger");
      live = 1;
    } else {
      $("#control").find("span").text("Start");
      $("#control").children().removeClass("btn-danger");
      clearInterval(timer);
      live = 0;

    };
    return false;

  });

  // Skype break

  /* $("#skipbreak").hide();
  $("#skipbreak a").click(function(){

    clearInterval(timer);
    $("#timer").data("value", "15000").hide().text("25:00").delay(1000).fadeIn(1000);
    $("#skipbreak").hide().delay(3000).fadeIn(1000);
    $("#skipbreak a").children("span").text("Začít znovu");

    setTimeout(updateStartButtonOn, 2000);

    return false;

  }); */


  // Number of cycles
  function updateCycles(){
    numberOfCycles++;
    $.cookie(date, numberOfCycles);
    $("#numberofcycles span").text(numberOfCycles);
  };

  // Part of cycle
  function whatIsName(){
    if(def == 1){
      var name = namePomodoro;
    } else {
      var name = nameBreak;
    };

    return name;
  };


  function setValue(){
    if(def == 1){
      timeSet = 1501000; // pomodoro in ms 1501000
      $("#name").children("span").text(whatIsName());
      $("#skipbreak a").children("span").text("Začít znovu");
    } else {
      timeSet = 300000; // break in ms  300000
      updateCycles();
      $("#name").children("span").text(whatIsName());
      $("#skipbreak a").children("span").text("Přeskočit přestávku");
    };

    $("#timer").data("value", timeSet);
  };

  setValue();

  function showNotification(){

    if(def == 1){
      var title = namePomodoro;
      var desc = descPomodoro;
      var img = "img/ico-work.png";
    } else {
      var title = nameBreak;
      var desc = descBreak;
      var img = "img/ico-break.png";
    };

    if(browserChrome == true){
      window.webkitNotifications.createNotification(img, title, desc).show();
    } else {
      alert(title + " | " + desc);
    };

    soundAlert.play();

  };


  var delay = 0;
  var correction = 0;

  function core(){

      var now, before = new Date();
      delay = 1000;

      timer = window.setInterval(function() {

        now = new Date();
        var elapsedTime = (now.getTime() - before.getTime());

        if(elapsedTime > delay){
          correction = elapsedTime - delay;
        } else {
          correction = 0;
        };

        var timeCounter = $("#timer").data("value");
        var updateTime = eval(timeCounter)- eval(1000 + correction);
        document.title = (formatTimeOfDay(updateTime)) + " | " + whatIsName();
        $("#timer").data("value", updateTime);
        $("#timer").text(formatTimeOfDay(updateTime));

        if(updateTime <= 0){

            if(def == 1){
              def = 2;
            } else {
              def = 1;
            };

            setValue();
            showNotification();

        }

        before = new Date();

    }, delay);

  };

});